package com.useeinfo.oa.open.mobile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.ApplicationModuleBiz;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.entity.ApplicationModule;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.security.biz.SystemAuthorityBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemAuthority;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @program: YiYouFuPlatform
 * @author: Taogq
 * @createDate: 2018-12-20
 * @createTime: 16:50:18
 */
@RestController
@RequestMapping("/api/mobile/manage/access")
public class UserAccessMsgManageAction {
    @Autowired
    private SystemAuthorityBiz systemAuthorityBiz;
    @Autowired
    private ApplicationModuleBiz applicationModuleBiz;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;

    /**
     * 获取用户应用和权限接口
     *
     * @return  修改用户session
     */
    @RequestMapping("/getAccess")
    public ResultDto userAccess(String enterpriseId) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (null == systemUser) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        Enterprise enterprise = enterpriseBiz.findModel(StringConverters.null2Long(enterpriseId));
        if (null == enterprise) {
            return ResultUtil.error("请传入正确的企业信息");
        }


        String systemUserHql = "select obj from SystemUser obj where obj.id=" + systemUser.getId() + "  and exists ( select ep from obj.enterpriseSet ep where ep.id=" + enterprise.getId() + ")";
        List<SystemUser> systemUserList = systemUserBiz.hqlExcute(systemUserHql, new QueryParam());
        if (CollectionUtils.isEmpty(systemUserList)) {//验证当前登录用户是否在企业中，以防用户乱操作
            return ResultUtil.error("当前用户不在该企业中，请确认");
        }

        String applicationHql = "select obj from ApplicationModule obj where obj.deleteStatus is false and exists(select o from obj.enterpriseSet o where o.id=" + enterpriseId + ")";
        List<ApplicationModule> applicationModuleList = applicationModuleBiz.hqlExcute(applicationHql);
        JSONObject applicationJSON;
        JSONArray applicationArray = new JSONArray();
        String authHql = "select obj from SystemAuthority obj left join obj.systemModule as sm where obj.deleteStatus is false and ( sm is null  or" +
                " sm.applicationModuleId in ( select al.id from  ApplicationModule al" +
                " where exists( select ep from al.enterpriseSet ep where ep.id=" + enterpriseId + ")))" +
                " and exists( select r from obj.roleSet r where r.id in ( select ure.systemRole.id from UserRoleEnterprise ure where " +
                " ure.enterprise.id=" + enterpriseId + " and ure.systemUser.id =" + systemUser.getId() + ")) ";
        List<SystemAuthority> authorityList = systemAuthorityBiz.hqlExcute(authHql);
        JSONArray authArray = new JSONArray();
        JSONObject authJSON;
        Boolean flag=false;

        for (SystemAuthority systemAuthority : authorityList) {
            authJSON = new JSONObject();
            if("ROLE_ENTERPRISE_DASHBOARD_PAGE".equals(systemAuthority.getAuthorityName())||"enterprise".equals(systemUser.getOperationRole())||"admin".equals(systemUser.getOperationRole())){//管理看板模块需要配置角色权限才能看到
                flag=true;
            }
            authJSON.put("authName", StringConverters.null2String(systemAuthority.getAuthorityName()));
            authJSON.put("authDesc", StringConverters.null2String(systemAuthority.getAuthorityDescription()));
            authArray.add(authJSON);
        }
        for (ApplicationModule applicationModule : applicationModuleList) {
            if((flag&&"DASHBOARD".equals(applicationModule.getRemark())) || !"DASHBOARD".equals(applicationModule.getRemark())||"enterprise".equals(systemUser.getOperationRole())||"admin".equals(systemUser.getOperationRole())){
                applicationJSON = new JSONObject();
                applicationJSON.put("applicationName", StringConverters.null2String(applicationModule.getApplicationName()));
                applicationJSON.put("applicationUrl", StringConverters.null2String(applicationModule.getUrl()));
                applicationJSON.put("applicationIcon", StringConverters.null2String(applicationModule.getIcon()));
                applicationJSON.put("applicationType", StringConverters.null2String(applicationModule.getApplicationTypeEnum()));
                applicationArray.add(applicationJSON);
            }
        }
        JSONObject result = new JSONObject();
        result.put("applications", applicationArray);
        result.put("auths", authArray);
        SessionKeyUtils.setSessionEnterprise(request, enterprise);
        return ResultUtil.success(result);
    }
}
